package com.huluobo.a2203kotlinjetpackdemo.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import java.lang.Exception

/**
 *  Created by LC on 2024/7/20.
 */
class RepoPagingSource(private val apiService: ApiService) : PagingSource<Int, Bean>() {
    override fun getRefreshKey(state: PagingState<Int, Bean>): Int? {
        return null
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, Bean> {
        return try {
            val page = params.key ?: 1 //当前的页码
            val pageSize = params.loadSize //当前页面中item的数量
            val repoResponse = apiService.searchRepos(page, pageSize) //发起网络请求的返回
            val repoItems = repoResponse.items //请求返回的bean的数据源
            val prevKey = if (page > 1) page - 1 else null //代表向前翻页的页码
            val nexKey = if (repoItems.isNotEmpty()) page + 1 else null //向后翻页的页码
            LoadResult.Page(repoItems, prevKey, nexKey)//paging在进行分页处理
        } catch (e: Exception) {
            LoadResult.Error(e)
        }
    }
}